package com.weather.MQTT.utils;

import com.weather.MQTT.callBack.MyMqttCallBack;
import com.weather.MQTT.utils.bean.MqttBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 *  mqtt工具类
 * @author 化粪池堵塞的凶手
 */
public class MqttUtil {
    private static final String TOPIC = "GouShengWeather";
    private MqttBean mqttBean;
    private Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    public void setMqttBean(MqttBean mqttBean) {
        this.mqttBean = mqttBean;
    }

    public MqttUtil() {

    }

    /**
     * 获取连接
     */
    public void getConnection(){
        // 创建连接参数
        MqttConnectOptions connOption = new MqttConnectOptions();
        // 在重新启动和重新连接时记住状态
        connOption.setCleanSession(false);
        // 10s超时
        connOption.setConnectionTimeout(10);
        // 设置会话心跳时间 单位为秒 服务器会每隔1.5*10秒的时间向客户端发送个消息判断客户端是否在线
        connOption.setKeepAliveInterval(20);
        try {
            mqttBean.getClient().connect(connOption);
        } catch (MqttException e) {
            e.printStackTrace();
        }
        if (mqttBean.getClient().isConnected()){
            logger.info("MQTT Connect Success");
        }
    }

    /**
     * 打开监听消息
     */
    public void enableAcceptor(){
        logger.info("enableAcceptor...  TOPIC:"+TOPIC);
        mqttBean.getClient().setCallback(new MyMqttCallBack(mqttBean.getClient()));
        try {
            mqttBean.getClient().subscribe(TOPIC);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }



    /**
     * 关闭连接
     */
    public void disable(){
        try {
            mqttBean.getClient().disconnect();
            mqttBean.getClient().close();
            logger.info("Close MQTT Client");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


}
